<template>
  <div class="flupplan">
    <!-- 表单功能 -->
    <div class="search">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="query.key" placeholder="参数名" clearable style="width: 240px;" />
        </el-form-item>
        <el-form-item>
          <el-button color="#b9e8e3" plain class="btn" @click="search">查询</el-button>
          <el-button color="#17b3a3" class="btn2" @click="addData">新增</el-button>
          <el-button class="btn2" type="danger" @click="getDelete(null)"
            :disabled="currentDeleteId.length == 0">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="table">
      <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%"
        @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="身份证" property="id" align="center">
        </el-table-column>
        <el-table-column property="code" label="随访编码" width="150" align="center" />
        <el-table-column property="name" label="随访标题" width="150" align="center" />
        <el-table-column property="sourceId" label="样本来源" width="120" align="center" />
        <el-table-column property="beginDate" label="开始时间" width="150" align="center" />
        <el-table-column property="endDate" label="结束时间" width="150" align="center" />
        <el-table-column property="rateNum" label="随访频率" width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.rateNum != null">{{ scope.row.rateNum }}次/{{ scope.row.rateUnit }}</span>
            <span v-if="scope.row.rateNum == null">null次/null</span>
          </template>
        </el-table-column>
        <el-table-column property="department" label="随访部门" width="150" align="center" />
        <el-table-column property="doctor" label="随访医生" width="100" align="center" />
        <el-table-column property="state" label="随访状态" width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.state == 0">进行</span>
            <span v-if="scope.row.state == 1">失访</span>
            <span v-if="scope.row.state == 2">死亡</span>
            <span v-if="scope.row.state == 3">延期</span>
          </template>
        </el-table-column>
        <el-table-column property="lastFlupDate" label="最后随访时间" width="150" align="center" />
        <el-table-column property="sumNum" label="随访总次数" width="100" align="center" />
        <el-table-column property="createOn" label="创建时间" width="150" align="center" />
        <el-table-column property="createBy" label="创建人" align="center" />
        <el-table-column property="modifiedOn" label="修改时间" width="150" align="center" />
        <el-table-column property="remark" label="备注" width="110" align="center" />
        <el-table-column fixed="right" label="操作" min-width="150" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button link type="primary" size="small" @click="getDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <page :pageParams="query" :total="total" @size-change="pageChange" @currentChange="handleCurrentChange" />

    <!-- 对话框 -->
    <div>
      <el-dialog v-model="dialogVisible" :title=title width="700">
        <div style="margin-left: 30px;margin-top: 20px;">
          <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" label-width="auto" style="max-width: 600px">
            <el-row gutter="20">
              <el-col :span="12">
                <el-form-item label="随访编码" prop="code">
                  <el-input v-model="ruleForm.code" placeholder="随访编码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="随访标题" prop="name">
                  <el-input v-model="ruleForm.name" placeholder="随访标题" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="20">
              <el-col :span="12">
                <el-form-item label="样本来源" prop="sourceId">
                  <el-select v-model="ruleForm.sourceId" placeholder="样本来源">
                    <el-option v-for="item in option" :key="item.value" :label="item.name" :value="item.idCard" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开始时间" prop="beginDate">
                  <el-date-picker v-model="ruleForm.beginDate" type="datetime" placeholder="开始时间" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="20">
              <el-col :span="12">
                <el-form-item label="结束时间" prop="endDate">
                  <el-date-picker v-model="ruleForm.endDate" type="datetime" placeholder="结束时间" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="随访频率" prop="rateNum">
                  <el-input-number v-model="ruleForm.rateNum" @change="handleChange" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="20">
              <el-col :span="12">
              </el-col>
              <el-col :span="12">
                <el-form-item label="频率单位" prop="rateUnit">
                  <el-select v-model="ruleForm.rateUnit" placeholder="频率单位">
                    <el-option v-for="item in optionUnit" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="20">
              <el-col :span="12">
                <el-form-item label="随访部门" prop="department">
                  <el-input v-model="ruleForm.department" placeholder="随访部门" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="随访医生" prop="doctor">
                  <el-input v-model="ruleForm.doctor" placeholder="随访医生" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="20">
              <el-col :span="12">
                <el-form-item label="随访状态" prop="state">
                  <el-select v-model="ruleForm.state" placeholder="随访状态">
                    <el-option v-for="item in optionState" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最后随访时间" prop="lastFlupDate">
                  <el-date-picker v-model="ruleForm.lastFlupDate" type="datetime" placeholder="最后随访时间" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="20">
              <el-col :span="12">
                <el-form-item label="随访总次数" prop="sumNum">
                  <el-input-number v-model="ruleForm.sumNum" @change="handleChange" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="ruleForm.remark" :rows="2" type="textarea" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <template #footer>
          <div class="dialog-footer" style="margin-top: 20px;">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button color="#17B2A2" @click="submitForm(ruleFormRef)">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>

  </div>
</template>

<script lang="ts" setup>

import { nextTick, onMounted, reactive, ref } from 'vue';
import {  ElMessage, ElMessageBox, TableInstance, type FormInstance, type FormRules } from 'element-plus'
import page from "@/views/oss/page.vue"
import { list, source, addNew, update, deleteData } from '@/api/flupplan';

// 传参
const query = reactive({
  t: Date.now(),
  page: 1,
  limit: 10,
  key: ''
})

// 多选-表格
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
  currentDeleteId.value = []
  for (const item of val) {
    currentDeleteId.value.push(item.id)
  }
}

// 数据列表
const total = ref(0)
const tableData: any = ref([])

function getList() {
  list(query).then(res => {
    console.log(res)
    tableData.value = res.page.list
    total.value = res.page.totalCount
  })
}

// 分页处理
const pageChange = (val: number) => {
  query.page = 1
  query.limit = val
  getList()
}
const handleCurrentChange = (val: number) => {
  query.page = val
  getList()
}

//查询
function search() {
  query.page = 1
  getList()
}

//对话框
const dialogVisible = ref(false)
const title = ref("")

// 表单校验
interface RuleForm {
  code: any,
  name: any,
  sourceId: any,
  beginDate: any,
  endDate: any,
  rateNum: any,
  rateUnit: any,
  department: any,
  doctor: any,
  state: any,
  lastFlupDate: any,
  sumNum: any,
  remark: any
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  code: '',
  name: '',
  sourceId: '',
  beginDate: '',
  endDate: '',
  rateNum: '',
  rateUnit: '',
  department: '',
  doctor: '',
  state: '',
  lastFlupDate: '',
  sumNum: '',
  remark: ''
})
const rules = reactive<FormRules<RuleForm>>({
  code: [
    { required: true, message: '随访编码不能为空', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '随访标题不能为空', trigger: 'blur' },
  ],
  sourceId: [
    { required: true, message: '样本来源不能为空', trigger: 'blur' },
  ],
  beginDate: [
    { required: true, message: '开始时间不能为空', trigger: 'blur' },
  ],
  endDate: [
    { required: true, message: '结束时间不能为空', trigger: 'blur' },
  ],
  rateNum: [
    { required: true, message: '随访频率不能为空', trigger: 'blur' },
  ],
  rateUnit: [
    { required: true, message: '频率单位不能为空', trigger: 'blur' },
  ],
  department: [
    { required: true, message: '随访部门不能为空', trigger: 'blur' },
  ],
  doctor: [
    { required: true, message: '随访医生不能为空', trigger: 'blur' },
  ],
  state: [
    { required: true, message: '随访状态不能为空', trigger: 'blur' },
  ],
  lastFlupDate: [
    { required: true, message: '最后随访时间不能为空', trigger: 'blur' },
  ],
  sumNum: [
    { required: true, message: '随访总次数不能为空', trigger: 'blur' },
  ],
})

// 样本来源
const option = ref('')
const sourceOptions: any = []
function getSource() {
  source(sourceOptions).then(res => {
    console.log(res, "样本来源")
    option.value = res.donorsInfo
  })
}

// 频率单位-对话框
const optionUnit = [
  {
    value: '日',
    label: '日',
  },
  {
    value: '周',
    label: '周',
  },
  {
    value: '月',
    label: '月',
  },
  {
    value: '年',
    label: '年',
  },
]

// 随访状态-对话框
const optionState = [
  {
    value: '0',
    label: '进行',
  },
  {
    value: '1',
    label: '失访',
  },
  {
    value: '2',
    label: '死亡',
  },
  {
    value: '3',
    label: '延期',
  },
]

//数字选择器
const handleChange = (value: number | undefined) => {
  console.log(value)
}

// 新增-打开对话框
function addData() {
  dialogVisible.value = true
  title.value = '新增'
  // 重置表单
  nextTick(() => {
    ruleFormRef.value.resetFields()
  })
}

// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}

// 日期格式化工具函数
const formatDateTime = (date: Date | string) => {
  if (!date) return '';
  const d = new Date(date);
  // 补零函数
  const pad = (num: number) => num.toString().padStart(2, '0');

  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};

// 确定-新增
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const formData = {
        ...ruleForm,
        id: title.value === "修改" ? currentEditId.value : undefined,
        beginDate: formatDateTime(ruleForm.beginDate),
        endDate: formatDateTime(ruleForm.endDate),
        lastFlupDate: formatDateTime(ruleForm.lastFlupDate)
      };

      const apiCall = title.value === "新增" ? addNew(formData) : update(formData);

      apiCall.then(res => {
        ElMessage({
          message: `${title.value}成功`,
          type: 'success',
        })
        dialogVisible.value = false
        getList()
      })
        .catch(err => {
          ElMessage.error(`${title.value}失败: ${err.message || '未知错误'}`)
        })
    }
  })
}

// 修改
const currentEditId = ref('');
const handleEdit = (row: any) => {
  dialogVisible.value = true
  title.value = "修改"
  currentEditId.value = row.id;
  nextTick(() => {
    Object.keys(ruleForm).forEach(key => {
      ruleForm[key] = row[key] ?? '';
    })
    ruleForm.beginDate = row.beginDate ? new Date(row.beginDate) : '';
    ruleForm.endDate = row.endDate ? new Date(row.endDate) : '';
    ruleForm.lastFlupDate = row.lastFlupDate ? new Date(row.lastFlupDate) : '';
  })
}

// 删除
const currentDeleteId = ref('') // 存储当前要删除的ID
// 确定删除
function getDelete(index: any) {
  let id = index ? [index] : currentDeleteId.value
  console.log(id, 'id');

  ElMessageBox.confirm(
    `确定对[id=${id}]进行[删除]操作？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    deleteData(id).then(res => {
      ElMessage.success('删除成功')
      getList()
    })
  })

}




// 加载数据
onMounted(() => {
  getList()
  getSource();
})

</script>

<style lang="scss" scoped>
.flupplan {
  .search {
    .btn {
      color: #5d5c5c;
    }

    .btn2 {
      color: #fff;
    }

  }
}

:deep .table {
  .el-table thead th {
    background-color: #fff !important;
    color: #909399;
  }

  .cell {
    text-align: center !important;
    font-size: 12px !important;
  }
}
</style>
